import { Modal } from '@kedacom/react-next'
import React, { useEffect, useState } from 'react'
import { useBasicInfoStore } from '../store'
import shallow from 'zustand/shallow'
import { fetchGetKeyAfterImport, fetchGetPersonalTemplate, fetchGetPersonalTemplates } from '@/api/template'
import { InfoIcon } from '@/pages/manager/blocks/monitor/style'
import { Confirm } from '@/components/Alert'
import { t } from 'i18next'
import { useCreateContentStore } from '../../../store'
import { clearCheckedMeetingRooms, removeRoomData } from '../store.room'
import useCheckAuthentication from '@/components/AuthenticationCheck/useCheckAuthentication'
import AuthenticationCheck from '@/components/AuthenticationCheck'
import { useMeetingParamsStore } from '../../meetingParams/store'
import { useMeetingPollStore } from '../../poll/store'
import { useMeetingMixStore } from '../../mix/store'
import { useMeetingDcsStore } from '../../dcs/store'
import { useMeetingLiveVideoStore } from '../../liveVideo/store'
import { useMeetingAiStore } from '../../ai/store'
import { initUser } from '../../user/utils'
import { transSelectUserItem } from '../translator'
import { CheckedIcon, StyledWrap } from './style'
import { useMeetingVmpStore } from '../../vmp/store'
import { userImport } from '../../user/store.combine'
import { useMeetingTVWallStore } from '../../tvwall/store'
import { vipSort2Users } from '../../../store.combine'
import { initReactVmp } from '../../vmp/store.combine'
export default function ImportTemplateModal() {
	const { _isImportTemplateShow, update } = useBasicInfoStore(
		(state) => ({
			_isImportTemplateShow: state._isImportTemplateShow,
			update: state.update,
		}),

		shallow
	)
	const [template, setTemplate] = useState<
		{
			id: string
			name: string
		}[]
	>([])
	const [curId, setCurId] = useState('')

	const {
		run: checkAuthentication,
		open: isAuthenticationOpen,
		setOpen: setIsAuthenticationOpen,
		successFn,
	} = useCheckAuthentication({ onlyDialog: true })

	useEffect(() => {
		if (_isImportTemplateShow) {
			setCurId('')
			fetchGetPersonalTemplates({ order: 1, count: 0, start: 0 }).then((res) => {
				let _arr = res?.data.map((j) => ({ id: j.template_id, name: j.name })) ?? []
				setTemplate(_arr)
			})
		}
	}, [_isImportTemplateShow])

	const handelImport = () => {
		if (!curId) return
		update({ _isImportTemplateShow: false })
		Confirm(t('导入模板将会覆盖之前的参数，是否继续？'), function () {
			fetchGetPersonalTemplate(curId).then(async (res) => {
				if (res.success) {
					const preKey = useCreateContentStore.getState().preKey
					const roomData = useBasicInfoStore.getState().roomData
					// 导入模板应当传入会议的key  返回值也将是会议的key
					await fetchGetKeyAfterImport(preKey, curId).then((data) => {
						useCreateContentStore.setState({ preKey: data })
					})
					//个人模板的数据导入
					const importPersonalTplData = () => {
						//初始化基本信息
						const { meetingFormular } = useBasicInfoStore.getState()
						useBasicInfoStore.setState({
							name: res.name ?? '',
							mobilePhone: res.mobile ?? '',
							phoneNO: res.telephone ?? '',
							hour: res.duration === 0 ? 4 : Math.floor(res.duration / 60),
							minute: res.duration === 0 ? 0 : res.duration % 60,
							superMtNum: !!res.enable_audience,
							speaker: res.speaker ? transSelectUserItem(res.speaker) : initUser,
							manager: res.chairman ? transSelectUserItem(res.chairman) : initUser,
							vipList: res.vips ?? [],
						})
						//导入模板的情况下，如果是例会，不能是永久会议；如果是非例会，按照模板中的值赋值
						if (!meetingFormular) {
							let _permanentMeeting = res.duration === 0 //导入模板是否是永久会议
							useBasicInfoStore.setState({ permanentMeeting: _permanentMeeting })
						}
						useMeetingParamsStore.getState().init(res) //初始化会议参数
						useMeetingPollStore.getState().init(res.poll) //初始化轮询
						useMeetingMixStore.getState().init(res.mix) //初始化混音
						useMeetingDcsStore.getState().init(res.dcs) //初始化数据协作
						useMeetingLiveVideoStore.getState().init(res.recorder) //初始化直播与录播
						useMeetingAiStore.getState().init(res.ai) //初始化ai
						initReactVmp(res.vmp) //初始化vmp
						useMeetingTVWallStore.getState().init(res.tv_wall)
						//导入模板成员初始化
						userImport({
							all: res.all_members ?? [],
							often: res.often_mts ?? [],
						})
						vipSort2Users()
					}
					if (res.duration === 0 && roomData) {
						//当前有会议的情况下，导入模板为永久会议，取消会议
						clearCheckedMeetingRooms(
							() => {
								checkEncryptedAuth(res.encrypted_auth, importPersonalTplData)
								update({ meetingCriteriaList: [] })
								removeRoomData()
							},
							() => {},
							t('模板更改了会议时间属性为永久,系统将自动释放原本锁定和预定的会议室，是否继续？')
						)
					} else {
						checkEncryptedAuth(res.encrypted_auth, importPersonalTplData)
					}
				} else {
					update({ _isImportTemplateShow: false })
				}
			})
		})
	}

	//编辑时由强认证状态导入非强认证模板,校验动态口令
	const checkEncryptedAuth = (val: 0 | 1, callback: Function) => {
		const meetingMoid = useCreateContentStore.getState().meetingMoid
		if (useMeetingParamsStore.getState().encryptedAuth && !val) {
			checkAuthentication(meetingMoid, (flag) => {
				if (flag) {
					//强认证密码验证通过，允许取消强认证
					useMeetingParamsStore.setState({ encryptedAuth: false })
				} else {
					//不通过，继续勾选强认证,且加密方式不变
					useMeetingParamsStore.setState({ encryptedAuth: true })
				}
				callback()
			})
		} else {
			callback()
		}
	}

	return (
		<Modal
			title={t('导入模板')}
			width={400}
			height={300}
			open={_isImportTemplateShow}
			okText={t('载入')}
			onOk={handelImport}
			onCancel={() => {
				update({ _isImportTemplateShow: false })
			}}
			cancelText={t('取消')}
		>
			<StyledWrap className="import-template-modal">
				<div className="content">
					{template.length === 0 ? (
						<div className="empty">
							<InfoIcon />
							{t('暂无模板')}
						</div>
					) : (
						<div>
							{template.map((item) => (
								<div
									key={item.id}
									className={`item ${curId === item.id ? 'selected' : ''}`}
									onClick={() => setCurId(item.id)}
								>
									<CheckedIcon className="select-icon"></CheckedIcon>
									{item.name}
								</div>
							))}
						</div>
					)}
				</div>
				{/* 
				AuthenticationCheck 
				请输入动态口令 弹窗
				
				*/}
				<AuthenticationCheck
					open={isAuthenticationOpen}
					setOpen={setIsAuthenticationOpen}
					callBack={successFn}
				/>
			</StyledWrap>
		</Modal>
	)
}
